package com.zhongke.cotrun.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Strings;
import com.zhongke.cotrun.mapper.ProjectInfoMapper;
import com.zhongke.cotrun.model.enums.EnumConfigType;
import com.zhongke.cotrun.model.pojo.*;
import com.zhongke.cotrun.service.CommonConfigService;
import com.zhongke.cotrun.service.ProjectInfoService;
import com.zhongke.cotrun.shiro.sys.shiro.ShiroUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * 作者 yhl
 * 日期 2020-01-05 02:02:19
 * 描述 ProjectInfo 服务实现
 */
@Service
public class ProjectInfoImpl implements ProjectInfoService {

    @Resource
    private ProjectInfoMapper projectInfoMapper;
    @Resource
    private CommonConfigService commonConfigService;

    /**
     * 根据主键删除数据
     *
     * @param projectId
     */
    @Override
    public int deleteByPrimaryKey(Integer projectId) {
        return projectInfoMapper.deleteByPrimaryKey(projectId);
    }

    @Override
    public Boolean cancelByPrimaryKey(Integer projectId) {
        return projectInfoMapper.cancelByPrimaryKey(projectId);
    }

    @Override
    public boolean approvalByPrimaryKey(Integer id, Integer state, String opinion) {
        String userName = ShiroUtils.getUserName();
        return projectInfoMapper.approvalByPrimaryKey(id, state, opinion,userName);
    }

    @Override
    public boolean deleteBatch(String ids) {
        return projectInfoMapper.deleteBatch(ids);
    }

    @Override
    public boolean recommendProject(String ids) {
        return projectInfoMapper.recommendProject(ids);
    }

    @Override
    public boolean setRecommend(Integer id, Integer state) {
        return projectInfoMapper.setRecommend(id,state);
    }

    @Override
    public boolean approvalPass(ProjectInfo record) {
        String userName = ShiroUtils.getUserName();
        record.setApprovalState(1);
        record.setApprovalUser(userName);
        record.setApprovalOpinion("");
        record.setApprovalTime(new Date());
        return projectInfoMapper.updateByPrimaryKeySelective(record)>0;
    }

    /**
     * 插入数据库记录
     *
     * @param record
     */
    @Override
    public int insertSelective(ProjectInfo record) {
        return projectInfoMapper.insertSelective(record);
    }

    /**
     * 插入数据库记录
     *
     * @param record
     */
    @Override
    public int insertSelectiveForHistory(ProjectInfo record) {
        if (record.getProjectId() != null && record.getProjectId() > 0) {
            // 更新
            return projectInfoMapper.updateByPrimaryKeySelective(record);
        }
        // 保存
        else {
            record.setCreateId(ShiroUtils.getUserId1());
            return projectInfoMapper.insertSelective(record);
        }
    }

    /**
     * 修改数据
     *
     * @param record
     */
    @Override
    public int updateByPrimaryKeySelective(ProjectInfo record) {
        return projectInfoMapper.updateByPrimaryKeySelective(record);
    }


    /**
     * 根据主键id查询
     *
     * @param projectId
     */
    @Override
    public ProjectInfoVo selectByPrimaryKey(Integer projectId) {

        ProjectInfoVo projectInfoVo = projectInfoMapper.selectByPrimaryKey(projectId);
        if (projectInfoVo == null) {
            return null;
        }
        parserExtDataForList(projectInfoVo);
        return parserExtData(projectInfoVo);
    }


    private List<String> handlerOneAreaList(List<Integer> codes, Integer configType) {
        List<String> areas = new ArrayList<>(codes.size());
        if (CollectionUtils.isNotEmpty(codes)) {
            CommonConfig config = commonConfigService.selectByPrimaryKey(configType);
            if (config == null) {
                return areas;
            }
            List<Item> items = JSON.parseArray(JSON.toJSONString(config.getConfig()), Item.class);

            List<String> list = handlerItem(items, codes);
            if (CollectionUtils.isNotEmpty(list)) {
                areas.addAll(list);
            }
        }
        return areas;
    }

    /**
     * 解析项目扩展数据
     *
     * @param projectInfoVo
     * @return
     */
    private ProjectInfoVo parserExtData(ProjectInfoVo projectInfoVo) {
        if (projectInfoVo == null) {
            return null;
        }
        projectInfoVo.setUseAreaStr(handlerOneAreaList(projectInfoVo.getUseArea(), EnumConfigType.USE_AREA.getCode()));
        projectInfoVo.setFruitTypeStr(handlerOneAreaList(projectInfoVo.getFruitType(), EnumConfigType.FRUIT_TYPE.getCode()));
        projectInfoVo.setProcessTypeStr(handlerOneAreaList(projectInfoVo.getProcessType(), EnumConfigType.PROCESS_TYPE.getCode()));
        projectInfoVo.setSkillAreaStr(handlerTwoAreaList(projectInfoVo.getSkillArea(), EnumConfigType.SKILL_AREA.getCode()));
        projectInfoVo.setFinancingTypeStr(handlerOneAreaList(projectInfoVo.getFinancingType(), EnumConfigType.FINANCING_TYPE.getCode()));
        return projectInfoVo;
    }

    /**
     * 解析项目扩展数据
     *
     * @param projectInfoVo
     * @return
     */
    private ProjectInfoVo parserExtDataForList(ProjectInfoVo projectInfoVo) {
        if (projectInfoVo == null) {
            return null;
        }
        projectInfoVo.setUseAreaStr(handlerOneAreaList(projectInfoVo.getUseArea(), EnumConfigType.USE_AREA.getCode()));
        return projectInfoVo;
    }

    private List<String> handlerItem(List<Item> items, List<Integer> codes) {
        List<String> list = new ArrayList<>();
        if (CollectionUtils.isEmpty(items) || CollectionUtils.isEmpty(codes)) {
            return list;
        }
        for (int j = 0; j < items.size(); j++) {
            for (int i = 0; i < codes.size(); i++) {
                if (!Objects.equals(items.get(j).getId(), codes.get(i))) {
                    continue;
                }
                list.add(items.get(j).getDesc());
                break;
            }
        }
        return list;
    }

    private List<String> handlerTwoAreaList(List<Integer> codes, Integer configType) {
        List<String> twoArea = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(codes)) {
            CommonConfig config = commonConfigService.selectByPrimaryKey(configType);
            if (config == null || CollectionUtils.isEmpty(config.getConfig())) {
                return twoArea;
            }
            List<Item> items = config.getConfig();
            items = JSON.parseArray(JSON.toJSONString(items), Item.class);
            for (int i = 0; i < items.size(); i++) {
                List<String> list = handlerItem(items.get(i).getList(), codes);
                if (CollectionUtils.isNotEmpty(list)) {
                    twoArea.addAll(list);
                }
            }
        }
        return twoArea;
    }

    @Override
    public List<ProjectInfoVo> listLast12Info() {
        List<ProjectInfoVo> list = projectInfoMapper.listLast12Info();
        return list;
    }

    /**
     * 根据主键id查询
     *
     * @param projectId
     */
    @Override
    public ProjectInfo selectAuditDetailByPrimaryKey(Integer projectId) {
        return projectInfoMapper.selectAuditDetailByPrimaryKey(projectId);
    }

    @Override
    public PageQueryResult<ProjectInfoVo> pageQueryProjectList(ProjectInfoVo query) {
        PageHelper.startPage(query.getPageIndex(), query.getPageSize());
        if (Strings.isNullOrEmpty(query.getSort())) {
            query.setSort("desc");
        }
        List<ProjectInfoVo> list = projectInfoMapper.queryProjectList(query);
        PageInfo pageInfo = new PageInfo(list);
        int count = (int) pageInfo.getTotal();
        return new PageQueryResult(count, list);
    }

    @Override
    public PageInfo pageQueryProjectListForManager(ProjectInfoVo query) {
        PageHelper.startPage(query.getPageIndex(), query.getPageSize());
        if (Strings.isNullOrEmpty(query.getSort())) {
            query.setSort("desc");
        }
        List<String> youWantList = query.getYourWant();
        if(youWantList!=null&&youWantList.size()>0){
            String youWant = youWantList.get(0);
            Collections.replaceAll(youWantList,youWant,"\""+youWant+"\"");
        }
        List<ProjectInfoVo> list = projectInfoMapper.queryProjectList(query);
        PageInfo pageInfo = new PageInfo(list);
        for(ProjectInfoVo pi:list){
            pi.setProcessTypeStr(handlerOneAreaList(pi.getProcessType(), EnumConfigType.PROCESS_TYPE.getCode()));
        }
        return pageInfo;
    }

    @Override
    public int queryUnApprovalCounts() {
        return projectInfoMapper.queryUnApprovalCounts();
    }


}